package com.ding.controller.webflow;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BaseElement;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.FlowElementsContainer;
import org.activiti.bpmn.model.Lane;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.SubProcess;
import org.activiti.bpmn.model.Task;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.editor.language.json.converter.BpmnJsonConverterUtil;
import org.activiti.editor.language.json.converter.util.JsonConverterUtil;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ManagementService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ding.service.WorkflowProcessDefinitionService;
import com.ding.service.WorkflowTraceService;
import com.ding.utils.Page;
import com.ding.utils.PageUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * 流程模型控制器
 *
 * @author guorui
 */
@Controller
@RequestMapping(value = "/workflow/model")
public class ModelController {


	protected Logger logger = LoggerFactory.getLogger(getClass());

	    @Autowired
	    private RepositoryService repositoryService;

	    @Autowired
	    protected TaskService taskService;

	    @Autowired
	    protected IdentityService identityService;
	    
	    @Autowired
	    protected WorkflowProcessDefinitionService workflowProcessDefinitionService;
	  
	    @Autowired
	    protected WorkflowTraceService traceService;
	    
	    @Autowired
	    ProcessEngine processEngine;
	    
	    @Autowired
	    ManagementService managementService;

	
    /**
     * 模型列表
     */
    @RequestMapping(value = "list")
    public ModelAndView modelList(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("workflow/model-list");
        
        
        Page<Model> page = new Page<Model>(PageUtil.PAGE_SIZE);
        int[] pageParams = PageUtil.init(page, request);
        
        ModelQuery modelQuery = repositoryService.createModelQuery();
        
        List<Model> list = modelQuery.listPage(pageParams[0], pageParams[1]);
        page.setResult(list);
        page.setTotalCount(modelQuery.count());
        mav.addObject("page", page);
        
        return mav;
    }

    /**
     * 创建模型
     */
    @SuppressWarnings("deprecation")
	@RequestMapping(value = "create", method = RequestMethod.POST)
    public void create(@RequestParam("name") String name, @RequestParam("key") String key, @RequestParam("description") String description,
                       HttpServletRequest request, HttpServletResponse response) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
            Model modelData = repositoryService.newModel();

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            description = StringUtils.defaultString(description);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName(name);
            modelData.setKey(StringUtils.defaultString(key));

            repositoryService.saveModel(modelData);
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));

            response.sendRedirect(request.getContextPath() + "/modeler.html?modelId=" + modelData.getId());
        } catch (Exception e) {
            logger.error("创建模型失败：", e);
        }
    }

    /**
     * 根据Model部署流程
     */
    @RequestMapping(value = "deploy/{modelId}")
    public String deploy(@PathVariable("modelId") String modelId, RedirectAttributes redirectAttributes) {
        try {
        	
        	
            Model modelData = repositoryService.getModel(modelId);
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;

            BpmnModel model = new MyBpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);

            String processName = modelData.getName() + ".bpmn20.xml";
            DeploymentBuilder builder = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes));
            Deployment deployment = builder.deploy();
            redirectAttributes.addFlashAttribute("message", "部署成功，部署ID=" + deployment.getId());
        } catch (ActivitiException | IOException e) {
        	redirectAttributes.addFlashAttribute("error", "部署失败-{"+e.toString()+"}");
        }
        return "redirect:/workflow/model/list";
    }

    /**
     * 导出model对象为指定类型
     *
     * @param modelId 模型ID
     * @param type    导出文件类型(bpmn\json)
     */
    @RequestMapping(value = "export/{modelId}/{type}")
    public void export(@PathVariable("modelId") String modelId,
                       @PathVariable("type") String type,
                       HttpServletResponse response) {
        try {
            Model modelData = repositoryService.getModel(modelId);
            BpmnJsonConverter jsonConverter = new MyBpmnJsonConverter();
            byte[] modelEditorSource = repositoryService.getModelEditorSource(modelData.getId());

            
            JsonNode editorNode = new ObjectMapper().readTree(modelEditorSource);
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);

            // 处理异常
            if (bpmnModel.getMainProcess() == null) {
                response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
                response.getOutputStream().println("no main process, can't export for type: " + type);
                response.flushBuffer();
                return;
            }

            String filename = "";
            byte[] exportBytes = null;

            String mainProcessId = bpmnModel.getMainProcess().getId();

            if (type.equals("bpmn")) {

                BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
                exportBytes = xmlConverter.convertToXML(bpmnModel);
                filename = mainProcessId + ".bpmn20.xml";
            } else if (type.equals("json")) {

                exportBytes = modelEditorSource;
                filename = mainProcessId + ".json";

            }

            ByteArrayInputStream in = new ByteArrayInputStream(exportBytes);
            IOUtils.copy(in, response.getOutputStream());

            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            response.flushBuffer();
            
        } catch (Exception e) {
            logger.error("导出model的xml文件失败：modelId={}, type={}", modelId, type, e);
        }
    }

    @RequestMapping(value = "delete/{modelId}")
    public String delete(@PathVariable("modelId") String modelId) {
        repositoryService.deleteModel(modelId);
        return "redirect:/workflow/model/list";
    }
    
    	//BpmnJsonConverter没有对isforcompensation的检查
	public	static class MyBpmnJsonConverter extends BpmnJsonConverter{
			
			
			@Override
				public void processJsonElements(JsonNode shapesArrayNode, JsonNode modelNode, BaseElement parentElement,
						Map<String, JsonNode> shapeMap, BpmnModel bpmnModel) {
					super.processJsonElements(shapesArrayNode, modelNode, parentElement, shapeMap, bpmnModel);
			//由于BaseBpmnJsonConverter 没有对isforcompensation属性的检查,所以手动检查
			for (JsonNode jsonNode : shapesArrayNode) {
				String elementId = BpmnJsonConverterUtil.getElementId(jsonNode);
				FlowElementsContainer container;
				
				if (parentElement instanceof Lane) {
					container=((Lane) parentElement).getParentProcess();
				}else if(parentElement instanceof Process || parentElement instanceof SubProcess){
					container=(FlowElementsContainer) parentElement;
				}else {
					return;
				}
				FlowElement flowElement = container.getFlowElement(elementId);
				
				if (flowElement!=null && flowElement instanceof Task) {
					Task t=(Task) flowElement;
					t.setForCompensation(new Boolean(JsonConverterUtil.getPropertyValueAsString("isforcompensation", jsonNode)));
				}
					
		  }
		  }
			
		}

}
